package net.tngou.tpage.action.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import net.tngou.tpage.action.BaseAction;
import net.tngou.tpage.jdbc.OrderType;
import net.tngou.tpage.jdbc.PageUtil;
import net.tngou.tpage.pojo.Basedata;
import net.tngou.tpage.pojo.Element;
import net.tngou.tpage.pojo.POJO;
import net.tngou.tpage.pojo.Result;
import net.tngou.tpage.pojo.Tempdata;
import net.tngou.tpage.service.BasedataService;
import net.tngou.tpage.util.Pinyin4j;
import net.tngou.tpage.util.StringUtil;

/**
 * 基础数据
 * @author tngou@tngou.net
 *
 */
public class BasedataApi extends BaseAction {

	
	/**
	 *公有数据
	 */
	@Override
	public void execute() throws ServletException, IOException {
		if(user==null){
			run_nologin();return;
		}
		
		if(ask.getId()==0){
			String keyword = ask.getKeyword();
			Map<String, Object> map = new HashMap<>();
			if(StringUtil.isNotEmpty(keyword))
			{
				map.put("id", keyword);
				map.put("text", keyword);
				map.put("pinyin", keyword+"%");
			}
			PageUtil page = service.getPage(ask.getPage(), ask.getRows(), "user=0 AND parentId=0",map, Basedata.class);
			printJson(toJsonPage(page));
		}else
		{
			List<?> list = service.getList("user=0 AND parentId="+ask.getId(), "seq",OrderType.ASC,Basedata.class);
			printJson(toJsonP(ask.getCallback(), JSON.toJSONString(list)));
		}
	}
	
	
	/**
	 * 私有数据
	 */
	public void my() {
		if(user==null){
			run_nologin();return;
		}
		if(ask.getId()==0){
			String keyword = ask.getKeyword();
			Map<String, Object> map = new HashMap<>();
			if(StringUtil.isNotEmpty(keyword))
			{
				map.put("id", keyword);
				map.put("text", keyword);
				map.put("pinyin", keyword.toUpperCase()+"%");
			}
			PageUtil page = service.getPage(ask.getPage(), ask.getRows(), "user="+user.getId()+" AND parentId=0",map, Basedata.class);
			printJson(toJsonPage(page));
		}else
		{
			List<?> list = service.getList("user="+user.getId()+" AND parentId="+ask.getId(), "seq",OrderType.ASC,Basedata.class);
			printJson(toJsonP(ask.getCallback(), JSON.toJSONString(list)));
		}
	}
	
	/**
	 * 基础数据-combobox
	 */
	public void combobox() {
		if(user==null){
			run_nologin();return;
		}
		if(ask.getId()==0){
			run_false("请求的参数不正确！");return;	
		}
		List<?> list = service.getList("parentId="+ask.getId(), "seq", OrderType.ASC, Basedata.class);
		printJson(toJsonP(ask.getCallback(), JSON.toJSONString(list)));
		
	}
	
	/**
	 * 基础数据-combotree
	 */
	public void combotree() {
		if(user==null){
			run_nologin();return;
		}
		if(ask.getId()==0){
			run_false("请求的参数不正确！");return;	
		}
		BasedataService service = new BasedataService();
		JSONArray array = service.combotree(ask.getId());
		printJson(toJsonP(ask.getCallback(), array.toJSONString()));		
				
	}
	
	/**
	 * 添加数据
	 */
	public void add() {
		if(user==null){
			run_nologin();return;
		}
		Basedata bean= getAsk(Basedata.class);
		if(isEmpty(bean.getText()))
		{
			run_false("请求的参数不正确！");return;	
		}
		if(user.getRole()==0)
		{
			bean.setUser(user.getId());
		}else
		{
			bean.setUser(0);//设置为公共数据
		}
		if(bean.getParentId()==0)
		{
			bean.setState("closed");
		}else
		{
			bean.setState("open");
		}
		bean.setPinyin(Pinyin4j.ToHanyuPinyinHead(bean.getText(), true));//设置拼音		
		if(bean.getParentId()!=0)
		{
			Basedata basedata = bean.get(bean.getParentId());
			if(basedata==null||bean.getUser()!=basedata.getUser())
			{
				run_false("请求数据错误！");return;
			}
			if("open".equals(basedata.getState()))
			{
				basedata.setState("closed");
				basedata.update();				
			}
		}
		
		long b = bean.save();
		if(b>0){	
			run_success("添加成功！",b);
		}else {run_false("添加失败！");return;}
		
	}
	
	/**
	 * 更新
	 */
	public void update() {
		if(user==null){
			run_nologin();return;
		}
		Basedata bean = getAsk(Basedata.class);
		if(ask.getId()==0)
		{
			run_false("请求的参数不正确！");return;	
		}
		Basedata basedata = bean.get(ask.getId());
		if(basedata==null)
		{
			run_false("请求的数据不正确！");return;	
		}
		if(!((basedata.getUser()==0&&user.getRole()==0)||basedata.getUser()==user.getId())){
			run_false("没有修改权限！");return;	
		}
		if(StringUtil.isNotEmpty(bean.getText()))basedata.setText(bean.getText());
		if(StringUtil.isNotEmpty(bean.getDescription()))basedata.setDescription(bean.getDescription());
		if(StringUtil.isNotEmpty(bean.getPinyin()))basedata.setPinyin(bean.getPinyin().toLowerCase());
		if(StringUtil.isNotEmpty(request.getParameter("seq")))basedata.setSeq(bean.getSeq());
		if(StringUtil.isNotEmpty(request.getParameter("value")))basedata.setValue(bean.getValue());
		long b = basedata.update();
		if(b>0){	
			run_success("修改成功！");
		}else {run_false("修改失败！");return;}
	}
	
	/**
	 * 删除
	 */
	public void delete() {
		if(user==null){
			run_nologin();return;
		}
		if(ask.getId()==0)
		{
			run_false("请求的参数不正确！");return;	
		}
		Basedata basedata = new Basedata().get(ask.getId());
		if(!((basedata.getUser()==0&&user.getRole()==0)||basedata.getUser()==user.getId())){
			run_false("没有操作权限！");return;	
		}
		int total = new Element().totalCount("beasedata="+ask.getId())+new Result().totalCount("beasedata="+ask.getId());
	    if(total>0)
	    {
	    	run_false("当前已有绑定数据,不能进行删除！");return;	
	    }
	    _delete(basedata);//删除数据
	    if(basedata.getParentId()!=0)//设置
	    {
	    	total=new Basedata().totalCount("parentId="+basedata.getParentId());
	    	if(total==0)
	    	{
	    		Basedata b = new Basedata().get(basedata.getParentId());
	    		if(b!=null)b.setState("open");
	    	}
	    }
	    run_success("删除成功！");
	}
	
	/**
	 * 拷贝数据
	 */
	public void copy() {
		if(user==null){
			run_nologin();return;
		}
		if(ask.getId()==0)
		{
			run_false("请求的参数不正确！");return;	
		}
		Basedata basedata = new Basedata().get(ask.getId());
		if(basedata==null)
		{
			run_false("请求的数据不正确！");return;	
		}		
		long userid=0;
		if(user.getRole()!=0)userid=user.getId();
		_copy(basedata, 0, userid); //拷贝数据
		 run_success("拷贝成功！");
	}
	
	
	/**
	 * 递归删除 基础数据
	 * @param basedata
	 */
	private void _delete(Basedata basedata) {
		
		@SuppressWarnings("unchecked")
		List<Basedata> list = (List<Basedata>) new Basedata().list(new HashMap<String,Object>(){{
			put("parentId", basedata.getId());
		}});
		list.forEach(e->{
			_delete(e);
		});
		basedata.delete();
		
	}
	
	
	/**
	 * 拷贝数据
	 * @param basedata 数据
	 * @param parentId 上级数据ID
	 * @param user 用户
	 */
	private void _copy(Basedata basedata,long parentId,long user) {
		basedata.setId(0);
		basedata.setParentId(parentId);
		basedata.setUser(user);
		long id = basedata.save();
		@SuppressWarnings("unchecked")
		List<Basedata> list = (List<Basedata>) new Basedata().list(new HashMap<String,Object>(){{
			put("parentId", basedata.getId());
		}});
		list.forEach(e->{
			_copy(e,id,user);
		});
		
	}
	
}
